<?php

namespace app\api\middleware;

use app\model\ConfigModel;
use app\model\UserModel;
use app\services\UserService;
use Exception;
use thans\jwt\exception\TokenInvalidException;
use thans\jwt\facade\JWTAuth;
use think\facade\Lang;

//验证权限
class CheckAuth
{

    protected $openApi = [
        'login/login',
        'login/sendSms',
        'login/register',
        'login/getSystemInfo',
        'login/getLanguage',
        'Login/sendSms',
        'Login/getAvatar',
        'UserAuth/resetPassword',
        'Upload/upload',
        'Home/getBanner',
        'Home/callUrl',  #支付回调地址
        'Home/callBack',  #支付回调地址
        'Home/callback_url',  #支付回调地址
        'Home/payOrderId',
        'home/callBack',  #支付回调地址

        'Home/payPalCallback',  # payPal 支付回调地址
        'home/payPalCallback',  # payPal 支付回调地址
        
        'Common/getConfig', // 系统配置

        // 'Common/getPayConfig', // 获取支付方式
        'Common/getAgreement',

        'Upload/uploadImage', //上传图片
        'Recharge/getRechargeParam',


        'mini/bindUid', // 绑定会员

        'Common/getCountry',
        'Common/getProvince',
        'Common/getCity',
     
        'Common/getSensitive', // 系统敏感词

    ];

    public function handle($request, \Closure $next)
    {
        // dump(app()->request->pathinfo());
        $lang = !empty($request->header('Accept-Language')) ? $request->header('Accept-Language') : env('lang.default_lang', 'zh-cn');
        Lang::setLangSet($lang);
        if (in_array(app()->request->pathinfo(), $this->openApi)) {
            return $next($request);
        }
        try {
            $forbiddenip = ConfigModel::getSensitive(['id' => 23]);
            if ($forbiddenip['value'] == 0) {
                return echoShutDown(lang('当前系统已临时关闭'), 400);
            }
            //查询ip 是否
//            $verify = UserService::getIp($request->ip());
//            if (!$verify) {
//                $config = ConfigModel::getSensitive(['id' => 17]);
//                return echoShutDown(lang('您是国内ip不能登录、请联系平台: ' . $config['value']), 10003);
//            }
            $jwtData = JWTAuth::auth();

        } catch (Exception $exception) {
            //token有误
            if (get_class($exception) == TokenInvalidException::class) {
                return echoShutDown(lang('user.loginError'), -1);
            }
            $errorMsgArr = [
                'Must have token' => lang('user.mustToken'),
                'The token is in blacklist.' => lang('user.blacklist'),
                'The token is expired.' => lang('user.expired'),
                'The token is in blacklist grace period list.' => lang('user.expired')
            ];
            return echoShutDown($errorMsgArr[$exception->getMessage()] ?? $exception->getMessage(), -1);
        }

        $userInfo = $jwtData['info']->getValue();
        //解密token中的用户信息
        $userInfo = str_encipher($userInfo, false, config('app.aes_token_key'));
        // 检查会员是否失效
        if (!$userInfo) {
            return echoShutDown(lang('user.loginError'), -1);
        }
        //解析json
        $userInfo = (array)json_decode($userInfo, true);
        $user = UserModel::where('id', $userInfo['user_id'])->field('id,status,is_examine')->find();
        if(empty($user)){
            return echoShutDown(lang('user.loginError'), -1);
        }
        if ($user['is_examine'] == 1) {
            return echoShutDown(lang('请等待审核通过后操作'), 400);
        }
        if ($user['status'] != 'normal') {
            return echoShutDown(lang('您已经被禁用了'), 400);
        }
        //已经登陆，将用户信息存入请求头
        $request->userInfo = $userInfo;
        $request->uid = $userInfo['user_id'];
        $request->gender = $userInfo['gender'];
        $request->userToken = JWTAuth::token()->get();
        return $next($request);
    }
}